﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using tea.Models;
using tea.DB;
using tea.BL;

namespace tea.Controllers
{
    [Authorize(Roles = BL사용자.ADMIN_OR_STAFF)]
    public class LectureController : Controller
    {
        [HttpGet]
        public ActionResult List()
        {
            using (var db = new DBDataContext()) {
                var 목록 = db.강의.OrderBy(p => p.중단).ThenBy(p => p.강의명).ToList();
                return View(목록);
            }
        }

        [HttpPost]
        [Util.AjaxOnly]
        public ActionResult Save(DB.강의 모델)
        {
            using (var db = new DBDataContext()) {
                var n = db.강의.FirstOrDefault(p => p.강의명 == 모델.강의명 && p.학기 == 모델.학기);
                if (n == null) 
                    db.강의.InsertOnSubmit(모델);
                else {
                    if (n.중단 == true)
                        n.중단 = false;
                    else
                        return Json(Consts.Ajax강의중복);
                }
                db.SubmitChanges();
                return Json(new AjaxSuccessModel(Url.Action("List", "Lecture")));
            }
        }

        [HttpPost]
        [Util.AjaxOnly]
        public ActionResult Delete(int[] id)
        {
            using (var db = new DBDataContext()) {
                foreach (var ID in id) {
                    var 항목 = db.강의.FirstOrDefault(p => p.ID == ID);
                    if (항목 == null) continue;
                    if (항목.지원_강의.Count > 0)
                        항목.중단 = true;
                    else
                        db.강의.DeleteOnSubmit(항목);
                }
                db.SubmitChanges();
                return Json(new AjaxSuccessModel(Url.Action("List", "Lecture")));
            }
        }

        [HttpPost]
        [Util.AjaxOnly]
        public ActionResult Undelete(int[] id)
        {
            using (var db = new DBDataContext()) {
                foreach (var ID in id) {
                    var 항목 = db.강의.FirstOrDefault(p => p.ID == ID);
                    if (항목 == null) continue;
                    항목.중단 = false;
                }
                db.SubmitChanges();
                return Json(new AjaxSuccessModel(Url.Action("List", "Lecture")));
            }
        }

    }
}

